package LinkedStack;

import LinkedListDemo.LinkedList;

import java.util.NoSuchElementException;

public class LinkedStack {
    Node head = new Node(0);
    int size;

    static class Node {
        int val;
        Node next;

        public Node(int val) {
            this.val = val;
            this.next = null;
        }
    }

    public boolean isEmpty() {
        return head.next == null;
    }

    public void push(int val) {
        Node node = new Node(val);
        node.next = head.next;
        head.next = node;
        size++;
    }

    public int pop() {
        if (isEmpty()) {
            throw new NoSuchElementException("栈为空");
        }
        int result = head.next.val;
        head.next = head.next.next;
        size--;
        return result;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();

        LinkedStack.Node curr = head.next;
        while (curr != null) {
            sb.append(curr.val).append(" ");
            curr = curr.next;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        LinkedStack stack = new LinkedStack();
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(6);

        String s = stack.toString();
        System.out.println(s);
        while(!stack.isEmpty()){
            System.out.println(stack.pop());
        }
    }
}
